#!/usr/bin/python
'''
Created on Apr 24, 2012
The code written herein is the sole property of the author and may not be edited, copied, or modified without explicit consent

@author: dstiffler
Project: C:/Users/dstiffler/workspace/TTT_Machine_Learning/tiktaktoe_machine_learning.py
'''

from itertools import chain


# Note: boards will be stored within a master hash-map {key = hashed representation of T/F/N, value = canonical TTTBoard}

class TTTBoard:
    
    def __init__(self, positionValues, initialWeight):
        self.board = positionValues
        self.weight = initialWeight    
          
def board_variations(startBoard):
    allRotations = [startBoard]
    
    allRotations = [[[allRotations[-1][-1 * rowIndex - 1][columnIndex] for rowIndex in range(3)] for columnIndex in range(3)] for rotationIndex in range(3)]
    
    allReflections = [[allRotations[reflectIndex][-1 * rowIndex - 1] for rowIndex in range(2)] for reflectIndex in range(1)]
    
    return allRotations + allReflections

def unhash_value_b3(hashedValue):
    unhashedString = ''
    
    while hashedValue > 0:
        current = divmod(hashedValue, 3)
        
        unhashedString = str(current[1]) + unhashedString
        hashedValue = current[0]
        
    canonicalBoard = []
    
    for rowIndex in range(2):
        rowData = []
        
        for columnIndex in range(2):
            currentValue = unhashedString[rowIndex * 3 + columnIndex]
            
            if currentValue == 0: rowData.append(None)
            elif currentValue == 1: rowData.append(True)
            else:   rowData.append(False)
            
        canonicalBoard.append(rowData)
        
        return canonicalBoard
    
def hash_value_b10(boardList):
     return int(str(chain.from_iterable(boardList)), 3)
    
def is_canonical(mlBoardInformation, testBoard):
    variations = board_variations(testBoard)
    
    for checkVariation in variations:
        if hash_value_b10(checkVariation) in mlBoardInformation.keys(): return False
        
    return True

def is_finished(testBoard):
    magicSquare = [[8, 3, 4], [1, 5, 9], [6, 7, 2]]
    
    for rowIndex in range(2):
        for columnIndex in range(2):
            
    
def populate_canonical_boards(mlBoardInformation, currentBoard, player, turnNumber):
    if is_finished(currentBoard):   return
    
    for rowIndex in range(2):
        for columnIndex in range(2):
            if currentBoard[rowIndex][columnIndex] == None:
                newBoard = currentBoard[:]
                newBoard[rowIndex][columnIndex] = player
                
                if is_canonical(newBoard):
                    mlBoardInformation[hash_value_b10(newBoard)] = TTTBoard(newBoard, )
    
    pass

mlBoardInformation = {}

if __name__ == '__main__':
    populate_canonical_boards()